package com.dy.course.service;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.dy.course.common.CacheManager;
import com.dy.course.common.Constant;
import com.dy.course.model.CourseNumTime;

/*
 * 监听器，用于项目启动的时候初始化信息
 */
@Service
public class StartAddCacheListener implements ApplicationListener<ContextRefreshedEvent> {
	
	private Logger logger = LoggerFactory.getLogger(StartAddCacheListener.class);

	@Autowired
	protected CacheManager redisCache;

	@Autowired
	private ICourseNumTimeService courseNumTimeService;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		logger.info("...【加载相关配置数据和数据库数据】...");
		// spring 启动的时候缓存城市和国家等信息
		if (event.getApplicationContext().getDisplayName().equals("Root WebApplicationContext")) {
			cacheCourseNumTimeList();
			cacheCourseMaxNumList();
		}
	}

	/**
	 * 
	 */
	public void cacheCourseNumTimeList() {
		logger.info("【redis缓存大学的每节课的时间】");
		List<CourseNumTime> numTimeList = courseNumTimeService.getAll();
		logger.info("【】查询结果,numTimeList={}",JSON.toJSONString(numTimeList));
		for (CourseNumTime numTime : numTimeList) {
			redisCache.set(
					Constant.CacheKey.COURSE_NUM_TIME + "#" + numTime.getUniversityId() + "#" + numTime.getNumber()+"#"+numTime.getType(),
					numTime);
		}
		
	}
	
	
	public void cacheCourseMaxNumList(){
		logger.info("【redis缓存大学的总节数】");
		//缓存所有大学的最大节课
		List<Map<String,Object>> list = this.courseNumTimeService.getCourseNums();
		logger.info("【】查询结果,list={}",JSON.toJSONString(list));
		for(Map<String,Object> map:list){
			Long id = (Long) map.get("id");
			Integer num = (Integer) map.get("num");
			redisCache.set(
					Constant.CacheKey.COURSE_MAX_NUM + "#" + id,
					num);
		}
	}

}
